package com.hong.qrpc.task;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author HQT
 * @Date 2022/8/10 12:01
 */
public class NettyTask<T> {
    private volatile T response;
    private ReentrantLock reentrantLock = new ReentrantLock();
    private volatile Condition condition = reentrantLock.newCondition();

    public T get() throws Exception {
        reentrantLock.lock();
        try {
            if (response != null) {
                return response;
            }
            condition.await();
            return response;
        } finally {
            reentrantLock.unlock();
        }
    }

    public T get(long timeout) throws InterruptedException {
        reentrantLock.lock();
        try {
            if (response != null) {
                return response;
            }
            condition.await(timeout, TimeUnit.MILLISECONDS);
            return response;
        } finally {
            reentrantLock.unlock();
        }

    }

    public void putAndNotify(T response) {
        reentrantLock.lock();
        try {
            this.response = response;
            condition.signalAll();
        } finally {
            reentrantLock.unlock();
        }
    }
}
